package com.exampl.health.controller;
import com.exampl.health.entity.User;
import com.exampl.health.service.UserService;
import com.exampl.health.util.FileUploadUtil;
import com.exampl.health.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/user")
public class UserDataController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户信息
     */
    @GetMapping("/info/{userId}")
    @ResponseBody
    public Result getUserInfo(@PathVariable("userId") Integer userId) {
        try {
            User user = userService.getUserById(userId);
            if (user != null) {
                // 不返回密码信息
                user.setPassword(null);
                return Result.success("获取用户信息成功", user);
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取用户信息失败");
        }
    }

    /**
     * 更新用户信息（不修改密码）
     */
    @PostMapping("/update")
    @ResponseBody
    public Result updateUserInfo(
            @RequestParam("userId") Integer userId,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "email", required = false) String email,
            @RequestParam(value = "avatarFile", required = false) MultipartFile avatarFile,
            HttpServletRequest request) {

        try {
            // 获取当前用户信息
            User currentUser = userService.getUserById(userId);
            if (currentUser == null) {
                return Result.error("用户不存在");
            }

            boolean hasChange = false;

            // 验证并更新用户名
            if (username != null && !username.isEmpty() && !username.equals(currentUser.getUsername())) {
                currentUser.setUsername(username);
                hasChange = true;
            }

            // 验证并更新邮箱
            if (email != null && !email.isEmpty()) {
                if (!isValidEmail(email)) {
                    return Result.error("邮箱格式不正确");
                }
                if (email.equals(currentUser.getEmail())) {
                    return Result.error("新邮箱不能与原邮箱相同");
                }
                // 检查邮箱是否已被其他用户使用
                if (userService.isEmailExists(email, userId)) {
                    return Result.error("邮箱已被其他用户使用");
                }
                currentUser.setEmail(email);
                hasChange = true;
            }

            // 处理头像上传
            if (avatarFile != null && !avatarFile.isEmpty()) {
                String avatarPath = FileUploadUtil.uploadAvatar(avatarFile, request);
                currentUser.setAvatar(avatarPath);
                hasChange = true;
            }

            // 如果没有需要更新的字段
            if (!hasChange) {
                return Result.error("没有需要更新的信息");
            }

            // 更新用户信息（不更新密码字段）
            boolean success = userService.updateUserWithoutPassword(currentUser);
            if (success) {
                // 不返回密码信息
                currentUser.setPassword(null);
                return Result.success("用户信息更新成功", currentUser);
            } else {
                return Result.error("用户信息更新失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 验证邮箱格式
     */
    private boolean isValidEmail(String email) {
        String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
        return Pattern.matches(emailRegex, email);
    }

    /**
     * 检查邮箱是否已存在
     */
    @PostMapping("/checkEmail")
    @ResponseBody
    public Result checkEmail(@RequestParam("email") String email,
                             @RequestParam(value = "userId", required = false) Integer userId) {
        try {
            boolean exists = userService.isEmailExists(email, userId);
            if (exists) {
                return Result.error("邮箱已被使用");
            } else {
                return Result.success("邮箱可用");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("检查邮箱失败");
        }
    }
}